package com.xindaoapp.happypet.adapter;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.BaseEntity;
import com.xindaoapp.happypet.bean.CommentInfo;
import com.xindaoapp.happypet.bean.PostLandlordInfo;
import com.xindaoapp.happypet.bean.PostLayerInfo;
import com.xindaoapp.happypet.bean.PostLayerInfos;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.ui.CommentActivity;
import com.xindaoapp.happypet.ui.DaShangRecordActivity;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.InputRegular;
import com.xindaoapp.happypet.utils.PostContentManager;

/**
 * 帖子详情适配器
 * 
 * @author xindaoapp
 * 
 */
public class PostsDetailAdapter extends XinDaoBaseAdapter<PostLayerInfo> {
    private final String mForumTid;
    private final boolean isOnlyAuthor;
    private final PostContentManager mPostContentManager;
    private final PostLandlordInfo mPostLandlordInfo;
    private final int mOrder;
    private View mOldPopView;
    private final Context mContext;
    private final onClickDaShang mClickDaShang;

    public PostsDetailAdapter(int mOrder, PostLandlordInfo mPostLandlordInfo, String mForumTid,
            boolean isOnlyAuthor, Activity context, List<PostLayerInfo> iniData, int pageNum,
            int pageSize, int res, int loadingRes) {
        super(context, iniData, pageNum, pageSize, res, loadingRes);
        this.mContext = context;
        this.mClickDaShang = (onClickDaShang) context;
        this.mOrder = mOrder;
        this.mPostLandlordInfo = mPostLandlordInfo;
        this.mForumTid = mForumTid;
        this.isOnlyAuthor = isOnlyAuthor;
        mPostContentManager = new PostContentManager(context, mForumTid);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent,
            final PostLayerInfo value) {
        ViewHolder holder = (ViewHolder) convertView.getTag();
        if (null == holder) {
            holder = new ViewHolder();
            holder.logoLandlord = (ImageView) convertView.findViewById(R.id.logo_landlord);
            holder.logoAdmin = (ImageView) convertView.findViewById(R.id.logo_manager);
            holder.icon = (ImageView) convertView.findViewById(R.id.user_icon);
            holder.username = (TextView) convertView.findViewById(R.id.user_name);
            holder.time = (TextView) convertView.findViewById(R.id.time);
            holder.tv_dashangcount = (TextView) convertView.findViewById(R.id.tv_dashangcount);
            holder.container = (LinearLayout) convertView.findViewById(R.id.container);
            holder.tools = convertView.findViewById(R.id.tools);
            holder.commentLine = convertView.findViewById(R.id.comment_line);
            holder.commentListView =
                    (LinearLayout) convertView.findViewById(R.id.comment_container);
            holder.examineMoreComment =
                    (TextView) convertView.findViewById(R.id.examine_more_comment);
            holder.reply = convertView.findViewById(R.id.reply);
            holder.tv_dashang = convertView.findViewById(R.id.tv_dashang);
            holder.tv_delete = convertView.findViewById(R.id.tv_delete);
            holder.popTools = convertView.findViewById(R.id.pop_tools);
            convertView.setTag(holder);
        }

        final View dashangCount = holder.tv_dashangcount;
        // TODO 禁掉版主功能
        // holder.tv_dashangcount.setVisibility(View.GONE);
        // holder.tv_dashang.setVisibility(View.GONE);
        // holder.tv_delete.setVisibility(View.GONE);

        // 判断pop中元素显影
        if (UserState.getUser() != null) {
            if (UserState.getUser().adminid == 1 || UserState.getUser().adminid == 2) {
                // 管理员
                holder.tv_dashang.setVisibility(View.VISIBLE);
                holder.tv_delete.setVisibility(View.VISIBLE);
            } else if (UserState.getUser().adminid == 3
                    && UserState.getUser().moderatefids.contains("'" + value.fid + "'")) {
                // 版主
                holder.tv_dashang.setVisibility(View.VISIBLE);
                holder.tv_delete.setVisibility(View.VISIBLE);

                // && !UserState.getUser().uid.equals(mPostLandlordInfo.authorid)) {
            } else if (UserState.getUser().uid.equals(value.authorid)) {
                // 自己评的
                holder.tv_delete.setVisibility(View.VISIBLE);
            } else {
                holder.tv_dashang.setVisibility(View.GONE);
                holder.tv_delete.setVisibility(View.GONE);
            }
        } else {
            holder.tv_dashang.setVisibility(View.GONE);
            holder.tv_delete.setVisibility(View.GONE);
        }
        holder.tv_dashang.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                hidePop();
                if (Integer.parseInt(value.ratesum) > 0) {
                    showHidePop(dashangCount, true);
                }
                mClickDaShang.goToDS(value);
            }
        });

        holder.tv_delete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                hidePop();
                if (Integer.parseInt(value.ratesum) > 0) {
                    showHidePop(dashangCount, true);
                }
                new AlertDialog.Builder(mContext).setMessage("确定删除该条回复?").setTitle("提示")
                        .setNegativeButton("删除", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                HappyPetApplication
                                        .get()
                                        .getMoccaApi()
                                        .deleteReply(mForumTid, value.pid,
                                                new IRequest<BaseEntity>() {

                                                    @Override
                                                    public void request(BaseEntity t) {
                                                        if (null != t && t.getResult().equals("0")) {
                                                            getResult().remove(position);
                                                            notifyDataSetChanged();
                                                            Toast.makeText(mContext, "删除回复成功",
                                                                    Toast.LENGTH_SHORT).show();
                                                        } else {
                                                            Toast.makeText(mContext, "删除回复失败",
                                                                    Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                });
                            }
                        }).setPositiveButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();

            }
        });

        holder.tv_dashangcount.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(mContext, DaShangRecordActivity.class);
                intent.putExtra(Constants.KEY_TAG, mForumTid);
                intent.putExtra(Constants.KEY_PID, value.pid);
                mContext.startActivity(intent);

            }
        });

        ImageLoader.getInstance().displayImage(value.userface, holder.icon);

        holder.icon.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ((PostDetailActivity) getBaseActivity()).startUserActivity(value.authorid,
                        value.author, value.userface);
            }
        });

        holder.username.setText(value.author);
        holder.time.setText(String.format("第%s楼  %s", value.position,
                CommonUtil.formatTimeForDetailCommon(value.addtime)));
        // TODO 这里报空指针
        if (value.ratesum == null) {
            value.ratesum = "0";
            holder.tv_dashangcount.setVisibility(View.GONE);
        } else if (Integer.parseInt(value.ratesum) <= 0) {
            holder.tv_dashangcount.setVisibility(View.GONE);
        } else {
            holder.tv_dashangcount.setVisibility(View.VISIBLE);
            holder.tv_dashangcount.setText("+" + value.ratesum);
        }

        if (value.commenttotal != 0) {
            holder.commentLine.setVisibility(View.VISIBLE);
            holder.commentListView.setVisibility(View.VISIBLE);
            parseCommentViews(value, holder.commentListView, value.commentarray);
            holder.examineMoreComment.setVisibility(View.VISIBLE);
            holder.examineMoreComment.setText(String.format("查看更多%s条回复", value.commenttotal));
            holder.examineMoreComment.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getBaseActivity(), CommentActivity.class);
                    intent.putExtra(Constants.KEY_LAYER_INFO, value);
                    intent.putExtra(Constants.KEY_LANDLORD_INFO, mPostLandlordInfo);
                    intent.putExtra(Constants.KEY_POST_TID, mForumTid);
                    getBaseActivity().startActivity(intent);
                }
            });
        } else {
            holder.commentLine.setVisibility(View.GONE);
            holder.commentListView.setVisibility(View.GONE);
            holder.examineMoreComment.setVisibility(View.GONE);
        }

        final View reply = holder.reply;
        final View popTools = holder.popTools;

        holder.popTools.setVisibility(View.GONE);
        holder.tools.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != mOldPopView) {
                    hidePop();
                    if (Integer.parseInt(value.ratesum) > 0) {
                        showHidePop(dashangCount, true);
                    }
                    // mOldPopView.setVisibility(View.GONE);
                    // mClickDaShang.showHidePop(true);
                    return;
                }
                showHidePop(dashangCount, false);
                mOldPopView = popTools;
                popTools.setVisibility(View.VISIBLE);
                reply.setVisibility(View.VISIBLE);
                reply.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        hidePop();
                        if (Integer.parseInt(value.ratesum) > 0) {
                            showHidePop(dashangCount, true);
                        }
                        Intent intent = new Intent(getBaseActivity(), CommentActivity.class);
                        intent.putExtra(Constants.KEY_LAYER_INFO, value);
                        intent.putExtra(Constants.KEY_LANDLORD_INFO, mPostLandlordInfo);
                        intent.putExtra(Constants.KEY_MODE_LOOK_COMMENT, false);
                        intent.putExtra(Constants.KEY_POST_TID, mForumTid);
                        getBaseActivity().startActivity(intent);
                    }
                });
            }
        });

        holder.reply.setVisibility(View.GONE);


        holder.container.removeAllViews();

        // ((PostDetailActivity) getBaseActivity()).setPersionPermission(holder.logoAdmin,
        // value.member_groupid);
        ((PostDetailActivity) getBaseActivity()).setLandlordLogo(holder.logoLandlord,
                value.authorid);

        mPostContentManager.parsePostContainer(holder.container, value.message, position);

        convertView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                hidePop();
                if (Integer.parseInt(value.ratesum) > 0) {
                    showHidePop(dashangCount, true);
                }
                ((PostDetailActivity) getBaseActivity()).switchBottomView(true);
                HappyPetApplication.mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        ((PostDetailActivity) getBaseActivity()).hideInputMethod();
                    }
                }, 100);
            }
        });
        return convertView;
    }


    public void hidePop() {
        if (mOldPopView != null) {
            // showHidePop(dashangCount,true);
            mOldPopView.setVisibility(View.GONE);
            mOldPopView = null;
        }
    }

    private void parseCommentViews(final PostLayerInfo value, LinearLayout commentContainer,
            List<CommentInfo> commentarray) {
        commentContainer.removeAllViews();
        for (int i = 0; i < commentarray.size(); i++) {
            final CommentInfo info = commentarray.get(i);
            View view = View.inflate(mContext, R.layout.item_post_detail_comment, null);
            String time = CommonUtil.formatTimeForDetailCommon(info.addtime);
            SpannableStringBuilder ssb =
                    CommonUtil.convetToHtml(CommonUtil.parseEmoji(String.format("%s：%s %s",
                            info.author, info.comment, time)), mContext);
            final TextView title = (TextView) view.findViewById(R.id.title);
            title.setText(new InputRegular(mContext).parseComment(info.author, time, ssb,
                    new IRequest<Boolean>() {

                        @Override
                        public void request(Boolean t) {
                            if (t) {
                                Intent intent = new Intent(mContext, MainActivity.class);
                                intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                                        UserInfoFragment.class.getCanonicalName());
                                Bundle bundle = new Bundle();
                                bundle.putString(Constants.KEY_UID, info.authorid);
                                bundle.putString(Constants.KEY_USERNAME, info.author);
                                bundle.putString(Constants.KEY_USERFACE, info.userface);
                                intent.putExtra(Constants.KEY_BUNDLE, bundle);
                                // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                getBaseActivity().startActivity(intent);
                            } else {
                                Intent intent =
                                        new Intent(getBaseActivity(), CommentActivity.class);
                                intent.putExtra(Constants.KEY_COMMENT_INFO, info);
                                intent.putExtra(Constants.KEY_LAYER_INFO, value);
                                intent.putExtra(Constants.KEY_LANDLORD_INFO, mPostLandlordInfo);
                                intent.putExtra(Constants.KEY_POST_TID, mForumTid);
                                getBaseActivity().startActivity(intent);
                            }
                        }
                    }));
            title.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getBaseActivity(), CommentActivity.class);
                    intent.putExtra(Constants.KEY_COMMENT_INFO, info);
                    intent.putExtra(Constants.KEY_LAYER_INFO, value);
                    intent.putExtra(Constants.KEY_LANDLORD_INFO, mPostLandlordInfo);
                    intent.putExtra(Constants.KEY_POST_TID, mForumTid);
                    getBaseActivity().startActivity(intent);
                }
            });
            title.setMovementMethod(LinkMovementMethod.getInstance());
            commentContainer.addView(view);
        }
    }

    @SuppressLint("NewApi")
    private void showReplyPopupWindow(View tool, float x, float y) {
        View view = View.inflate(mContext, R.layout.popupwindow_reply, null);
        PopupWindow window =
                new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        window.setBackgroundDrawable(new ColorDrawable(mContext.getResources().getColor(
                R.color.transparent)));
        window.setFocusable(true);
        window.showAtLocation(tool, Gravity.LEFT, (int) x, (int) y);
    }

    class ViewHolder {
        ImageView icon;
        TextView username;
        /** 发表时间 */
        TextView time;
        TextView tv_dashangcount;
        /** 内容区域 */
        LinearLayout container;
        LinearLayout commentListView;
        View popTools;
        View tools;
        View reply, tv_dashang, tv_delete;
        TextView examineMoreComment;
        ImageView logoAdmin;
        ImageView logoLandlord;
        View commentLine;
    }

    @Override
    public void nextPage(int start, int size,
            final ILoadNextPageData<PostLayerInfo> iLoadNextPageData) {
        super.nextPage(start, size, iLoadNextPageData);
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getPostLayerDetail(UserState.getUserUid(), mForumTid, isOnlyAuthor ? "1" : "", "",
                        start, size, mOrder, new IRequest<PostLayerInfos>() {

                            @Override
                            public void request(PostLayerInfos t) {
                                iLoadNextPageData.loadNextPageData(t == null ? null : t.postarray);
                            }
                        });
    }

    @Override
    public boolean isCheckFirstPage() {
        return false;
    }

    public void onDestory() {
        mPostContentManager.stopPlayback();
    }

    public interface onClickDaShang {
        public void goToDS(PostLayerInfo info);
    }

    public void showHidePop(View view, boolean isShow) {
        view.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }


}
